package com.android.minetopin;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.minetopin.activity.BaseWeb;
import com.android.minetopin.activity.mine.LoginActivity;
import com.android.minetopin.app.BaseActivity;
import com.android.minetopin.fragment.Fragment1;
import com.android.minetopin.fragment.Fragment4;
import com.android.minetopin.fragment.Fragment5;
import com.android.minetopin.fragment.Fragment_NewProduct;
import com.android.minetopin.fragment.member.Fragment_SeaAmoy;
import com.android.minetopin.model.member.MainADData;
import com.android.minetopin.model.member.MainADDataCallback;
import com.android.minetopin.pojo.BroadcastPojo;
import com.android.minetopin.utils.ConstantsUrl;
import com.android.minetopin.utils.HttpUtils;
import com.android.minetopin.utils.LoginState;
import com.android.minetopin.utils.ObjectUtils;

import java.util.HashMap;

import okhttp3.Call;

/**
 * 主页
 */

public class MainActivity extends BaseActivity {

    private int index;
    private int currentTabIndex;
    private ImageView[] imagebuttons;
    private TextView[] textviews;
    private boolean isExit;
    private MainActivity mcontext;
    Handler mHandler = new Handler();
    private AlertDialog adDialog;
    private boolean networkConnected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.android.minetopin.R.layout.activity_main);
        mcontext = MainActivity.this;
        initUI();
    }
    public void initUI() {
        changeFragment();
        setTabSelect(0);
        getADData();
    }

    private void getADData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        if (networkConnected) {
            HashMap<String, String> map = new HashMap<>();
            map.put("typeid", "88");
            HttpUtils.get(address, map, dataCallback);
        }
    }

    private String anurl;
    private String adPath;
    MainADDataCallback dataCallback = new MainADDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(MainADData response, int id) {
            if (response.getCode() == 0) {
                MainADData.DataBean data = response.getData();
                if(data !=null&&data.getAd()!=null){
                    if(data.getAd().get(0)!=null){
                        adPath = data.getAd().get(0).getPath();
                        anurl = data.getAd().get(0).getAnurl();
                        if(adPath!=null&&!adPath.equals("")){
                            showAdDialog();
                        }
                    }
                }
            }
        }
    };


    private DataChange dataChange;

    public void setData(DataChange dataChange) {
        this.dataChange = dataChange;
    }

    public interface DataChange {
        void setDataChange(int curr);
    }

    private void ONscroll(int curr) {
        if (dataChange != null) {
            dataChange.setDataChange(curr);
        }
    }

    private Fragment Fragment1, Fragment2, Fragment3, Fragment4, Fragment5;

    public void setTabSelect(int i,Object object){
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (i) {
            case 0:
                Fragment1 = manager.findFragmentByTag("TAG1");
                hideTab(transaction);
                if (Fragment1 == null) {
                    Fragment1 = new Fragment1();
                    transaction.add(R.id.fragment_container, Fragment1, "TAG1");
                } else {
                    transaction.show(Fragment1);
                }

                if(object!=null&& object instanceof BroadcastPojo){
                    BroadcastPojo  broadcastPojo = (BroadcastPojo)object;
                    ((Fragment1)Fragment1).ChangeTabHost(broadcastPojo.X1.toString());

                }

                break;
            case 1:
                Fragment2 = manager.findFragmentByTag("TAG2");
                hideTab(transaction);
                if (Fragment2 == null) {
                    Fragment2 = new Fragment_NewProduct();
                    transaction.add(com.android.minetopin.R.id.fragment_container, Fragment2, "TAG2");
                } else {
                    transaction.show(Fragment2);
                }
                break;
            case 2:
                Fragment3 = manager.findFragmentByTag("TAG3");
                hideTab(transaction);
                if (Fragment3 == null) {
                    Fragment3 = new Fragment_SeaAmoy();
                    transaction.add(R.id.fragment_container, Fragment3, "TAG3");
                } else {
                    transaction.show(Fragment3);
                }
                break;
            case 3:
                Fragment4 = manager.findFragmentByTag("TAG4");
                hideTab(transaction);
                if (Fragment4 == null) {
                    Fragment4 = new Fragment4();
                    transaction.add(R.id.fragment_container, Fragment4, "TAG4");
                } else {
                    transaction.show(Fragment4);
                }
                break;
//                    Fragment4 = manager.findFragmentByTag("TAG4");
//                    hideTab(transaction);
//
//                if (LoginState.getInstance().isLogin(mcontext)) {
//                    if (Fragment4 == null) {
//                        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
//                        {
//                         permissionList.clear();
//                            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
//                        }
//                        String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
//                        MyLog.e("oonzone",zone);
//                        if(zone.equals("")||zone==null) {
//
//                            if(!permissionList.isEmpty())
//                            {
//                                String [] permissions = permissionList.toArray(new String[permissionList.size()]);
//                                ActivityCompat.requestPermissions(MainActivity.this,permissions,1);
//                            }
//                            else
//                            {
//                                requestLocation();
//                            }
//
//                        }
//                        else
//                            {
//                                Fragment4 = new Fragment_SameCity_Service();
//                                transaction.add(R.id.fragment_container, Fragment4, "TAG4");
//                        }
//                    } else {
//                        transaction.show(Fragment4);
//                    }
//               }
//                else
//            {
//
//                int requestCode = 2;
//                startActivityForResult(new Intent(mcontext, LoginActivity.class),requestCode);
//
//            }
//                break;
            case 4:
                Fragment5 = manager.findFragmentByTag("TAG5");
                hideTab(transaction);
                if (Fragment5 == null) {
                    Fragment5 = new Fragment5();
                    transaction.add(R.id.fragment_container, Fragment5, "TAG5");
                } else {
                    ONscroll(1);
                    transaction.show(Fragment5);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    public void setTabSelect(int i) {
        setTabSelect(i,null);

    }

        private void hideTab(FragmentTransaction transaction) {
        if (Fragment1 != null) {
            transaction.hide(Fragment1);
        }
        if (Fragment2 != null) {
            transaction.hide(Fragment2);
        }
        if (Fragment3 != null) {
            transaction.hide(Fragment3);
        }
        if (Fragment4 != null) {
            transaction.hide(Fragment4);
        }
        if (Fragment5 != null) {
            transaction.hide(Fragment5);
        }
    }

    private void changeFragment() {
        imagebuttons = new ImageView[5];
        imagebuttons[0] = (ImageView) findViewById(com.android.minetopin.R.id.mian_tab_img_1);
        imagebuttons[1] = (ImageView) findViewById(com.android.minetopin.R.id.mian_tab_img_2);
        imagebuttons[2] = (ImageView) findViewById(com.android.minetopin.R.id.mian_tab_img_3);
        imagebuttons[3] = (ImageView) findViewById(com.android.minetopin.R.id.mian_tab_img_4);
        imagebuttons[4] = (ImageView) findViewById(com.android.minetopin.R.id.mian_tab_img_5);
        imagebuttons[0].setSelected(true);
        textviews = new TextView[5];
        textviews[0] = (TextView) findViewById(com.android.minetopin.R.id.mian_tab_tv_1);
        textviews[1] = (TextView) findViewById(com.android.minetopin.R.id.mian_tab_tv_2);
        textviews[2] = (TextView) findViewById(com.android.minetopin.R.id.mian_tab_tv_3);
        textviews[3] = (TextView) findViewById(com.android.minetopin.R.id.mian_tab_tv_4);
        textviews[4] = (TextView) findViewById(com.android.minetopin.R.id.mian_tab_tv_5);
        textviews[0].setTextColor(0xFFFF2741);
    }
    //改变主界面的fragment
    public  void ChangeMainFragment(int type)
    {
        index = type;
        imagebuttons[currentTabIndex].setSelected(false);
        imagebuttons[index].setSelected(true);
        textviews[currentTabIndex].setTextColor(0xFF333333);
        textviews[index].setTextColor(0xFFFF2741);
        currentTabIndex = index;
        setTabSelect(type);
    }
    /**
     * 跳转到主页的 某了商品列表切换
     * @param type
     * @param id
     */
    public  void ChangeMainFragmentTabHost(int type,Object broadcastPojo)
    {
        index = type;
        imagebuttons[currentTabIndex].setSelected(false);
        imagebuttons[index].setSelected(true);
        textviews[currentTabIndex].setTextColor(0xFF333333);
        textviews[index].setTextColor(0xFFFF2741);
        currentTabIndex = index;
        setTabSelect(type,broadcastPojo);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode)
        {
            case 1:
                String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
                if(!zone.equals("")) {
                    index = 3;
                    setTabSelect(3);
                }
                else {
                    index = 0;
                    setTabSelect(0);
                }
                imagebuttons[currentTabIndex].setSelected(false);
                imagebuttons[index].setSelected(true);
                textviews[currentTabIndex].setTextColor(0xFF333333);
                textviews[index].setTextColor(0xFFFF2741);
                currentTabIndex = index;
                    break;
            case 2:
                index = 0;
                imagebuttons[currentTabIndex].setSelected(false);
                imagebuttons[index].setSelected(true);
                textviews[currentTabIndex].setTextColor(0xFF333333);
                textviews[index].setTextColor(0xFFFF2741);
                currentTabIndex = index;
                setTabSelect(0);
                break;

        }
    }
    public void onTabClicked(View v) {
        switch (v.getId()) {
            case com.android.minetopin.R.id.mian_tab_rl_1:
                index = 0;
                setTabSelect(0);
                break;
            case com.android.minetopin.R.id.mian_tab_rl_2:
                index = 1;
                setTabSelect(1);
                break;
            case com.android.minetopin.R.id.mian_tab_rl_3:
                index = 2;
                setTabSelect(2);
                break;
            case com.android.minetopin.R.id.mian_tab_rl_4:

                index = 3;
                setTabSelect(3);
                break;
            case com.android.minetopin.R.id.mian_tab_rl_5:
                index = 4;
                setTabSelect(4);
                break;
        }
        imagebuttons[currentTabIndex].setSelected(false);
        imagebuttons[index].setSelected(true);
        textviews[currentTabIndex].setTextColor(0xFF333333);
        textviews[index].setTextColor(0xFFFF2741);
        currentTabIndex = index;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                SharedPreferences sp = getSharedPreferences("time", 0);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                System.exit(0);
            } else {
                ObjectUtils.toast(mcontext, "再按一次就可以退出了");
                isExit = true;
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showAdDialog() {
        adDialog = new AlertDialog.Builder(mcontext).create();
        Window window =  adDialog.getWindow();
        //qingxun write.
        window.setDimAmount(0.5f);//设置昏暗度为0
        // 兼容6.0背景问题
        window.setBackgroundDrawableResource(android.R.color.transparent);
        adDialog.setCanceledOnTouchOutside(false);
        adDialog.show();

        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_main_ad, null);
        ImageView close = (ImageView) v.findViewById(R.id.dialog_close);
        ImageView img = (ImageView) v.findViewById(R.id.dialog_img_ad);
        ObjectUtils.photo2(mcontext,adPath,img);
        close.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        adDialog.dismiss();
                                    }
                                }
        );
        img.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        adDialog.dismiss();
                                        if(anurl==null||anurl.equals("")){
                                            return;
                                        }
                                        if (LoginState.getInstance().isLogin(mcontext)) {
                                            Intent intent = new Intent(mcontext, BaseWeb.class);
                                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_WEB_URL, anurl);
                                            startActivity(intent);
                                        } else {
                                            startActivity(new Intent(mcontext, LoginActivity.class));
                                        }
                                    }
                                }
        );
        adDialog.getWindow().setContentView(v);
    }

}
